package com.sxkf.template.service.impl;

import com.sxkf.template.entity.Prize;
import com.sxkf.template.entity.UserPrize;
import com.sxkf.template.mapper.PrizeMapper;
import com.sxkf.template.mapper.UserPrizeMapper;
import com.sxkf.template.service.UserPrizeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.RedisUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Random;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 杨玉龙
 * @since 2025-01-04 18:08:25
 */
@Service
public class UserPrizeServiceImpl extends ServiceImpl<UserPrizeMapper, UserPrize> implements UserPrizeService {
    @Resource
    private PrizeMapper prizeMapper;
    @Resource
    private RedisUtils redisUtils;

    private static final Random random = new Random();

    @Override
    public synchronized Prize lottery(String userId) {


        List<Prize> prizes = prizeMapper.selectList(null);
        Prize prize = draw(prizes);
        if (prize != null){
            UserPrize userPrize = new UserPrize();
            userPrize.setUserId(userId);
            userPrize.setState("0");
            userPrize.setPrizeId(prize.getId());
            userPrize.setPrizeName(prize.getName());
            userPrize.setPrizeImg(prize.getImage());
            save(userPrize);
        }
        return prize;
    }

    private Prize draw(List<Prize> prizes) {
        double randomValue = random.nextDouble();
        double cumulativeProbability = 0.0;

        for (Prize prize : prizes) {
            cumulativeProbability += prize.getProbability();
            if (randomValue <= cumulativeProbability) {
                return prize;
            }
        }
        return null; // 如果没有中奖
    }
}
